package com.gzh.permissionslibrary

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.PermissionChecker
import java.util.*

object PermissionsUtil {
    private val listenerMap = HashMap<String, PermissionListener>()

    /**
     * 申请授权
     *
     * @param context
     * @param listener
     * @param permission 需要申请授权的权限
     */
    fun requestPermission(
        context: Context, listener: PermissionListener, permission: Array<String>
    ) {
        if (Build.VERSION.SDK_INT < 23) {
            listener.permissionGranted(permission)
        } else {
            if (hasPermission(context, *permission)) {
                listener.permissionGranted(permission)
                return
            }
            val key = System.currentTimeMillis().toString()
            listenerMap[key] = listener
            val intent = Intent(context, PermissionActivity::class.java)
            intent.putExtra("permission", permission)
            intent.putExtra("key", key)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }

    /**
     * 判断权限是否授权
     *
     * @param context
     * @param permissions
     * @return
     */
    internal fun hasPermission(context: Context, vararg permissions: String): Boolean {
        if (permissions.isEmpty()) {
            return false
        }
        for (per in permissions) {
            val result = PermissionChecker.checkSelfPermission(context, per)
            if (result != PermissionChecker.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * 判断一组授权结果是否为授权通过
     *
     * @param grantResult
     * @return
     */
    internal fun isGranted(vararg grantResult: Int): Boolean {
        if (grantResult.isEmpty()) {
            return false
        }
        for (result in grantResult) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false
            }
        }
        return true
    }

    /**
     * @param key
     * @return
     */
    internal fun fetchListener(key: String): PermissionListener? {
        return listenerMap.remove(key)
    }
}